package scala.for_the.impatient

import scala.collection.mutable.ArrayBuffer

/**
  * Created by shichen on 2017/5/24.
  */
object ch03_array extends App{
  t_FixedArray()
  t_NonFixedArray()

  def t_FixedArray(): Unit ={
    val nums = new Array[Int](10) //都初使化0
    val ar = new Array[String](100) //初始化为null
    val s = Array("hello","world") //长度为2，类型是推断出来的，已提供初始值就不需要new了
    s(0) = "goodbye"
    s(0) = "goodbye2" //修改是内容，不是其引用值
    println("fixed array: " + s.mkString(" ") + ", toBuffer: " + s.toBuffer.mkString(","))
  }

  def t_NonFixedArray(): Unit = {
    val b = ArrayBuffer[Int]()
    val b2 = new ArrayBuffer[Int]
    b += 1
    b += (2,3,4) // 追加多个元素，以括号包起来
    b ++= Array(5,6,7)
    b.trimEnd(5) //移除最后5个元素
    println("after trim:" + b.mkString(" ") + ", max: " + b.max + ", sum: " + b.sum)

    //插入并不高效，需要平移
    b.insert(1,4) //下标1前插入4，下标从0开始
    println(b.toArray.mkString(" "))
    b.insert(2,3,5) // 下标2前插入多个
    println(b.toString()) // ArrayBuffer(1, 4, 3, 5, 2)

    //遍历
    for (i<- 0 until b.length) {
      println(i + ": " + b(i))
    }
    //每2个元素一跳
    for (i<- 0 until (b.length,2)) {
      println(i + " -> " + b(i))
    }
    //如果不用到下标，可直接访问元素，类似 c++ for loop 
    for (e <- b) {
      println("-> " + e)
    }

    //产生新数组
    val c = for (e <- b) yield 2 * e
    println("after yield: " + c)
    val d = for (elem <- b if elem % 2 == 0) yield  2*elem
    println("after yield by guard " + d)

    //val bSorted = b.sorted(_ < _)
    //println("after sorted, create a new arrayBuffer: " + bSorted.mkString(" "))
  }
}
